//统一数据库调用接口
(function(root,factory){
	if (typeof exports === 'object') {
        // Node. 
        var util=require("../diqye-util"),
        s=require("../string"),
        fillMthod=require("../methods/sqlFillMethod"),
        borderSyntax=require("../syntaxs/borderSyntax"),
        sqlMethod=require("../methods/sqlMethod");
        module.exports = factory.call(root,util,s,borderSyntax,fillMthod,sqlMethod);
    }
}(this,function(utilfn,s,borderSyntax,fillMthod,sqlMethod){
	function diqye(type,options){
		return diqye.database(type,options);
	}

	function sqlstr(sql,data){
		var start = borderSyntax.start;
		borderSyntax.start="${";
		sql=s(sql).setMethod(fillMthod).fill(data);
		borderSyntax.start="#{";
		sqlMethod.sqlData=[];
		sql=s(sql).setMethod(sqlMethod).fill(data);
		borderSyntax.start=start;
		return {
			sql:sql,
			data:sqlMethod.sqlData
		}

	}
	diqye.database = utilfn.decorator("database",{
		/*
			var db = database("sqlite3",{url:"c:a.db",username:null,password:null,port:null});
		*/
		init:function(options){
			this.options = options;
		},
		open:function(){
			throw "由子类实现";
		},
		close:function(){
			throw "由子类实现";
		},
		/*
			var db = database("sqlite3",{});
			db.open()
			db.trans(function(db){
				db.run.....
				db.all....
			});
			db.close()
		*/
		trans:function(fn){
			throw "由子类实现";
		},
		run:function(sql,data){
			if(data ==null){
				return this._run(sql);
			}else{
				var r=sqlstr(sql,data);
				return this._run(r.sql,r.data);
			}
		},
		_run:function(sql,data){
			throw "由子类实现";
		},
		first:function(sql,data,fn){
			if(typeof data == "function"){
				fn=data;
			}
			if(data==null){
				return this._first(sql,fn);
			}
			var r=sqlstr(sql,data);
			return this._first(r.sql,r.data,fn);
		},
		_first:function(sql,data,fn){
			throw "由子类实现";
		},
		all:function(sql,data,fn){
			if(typeof data == "function"){
				fn=data;	
				data=null;
			}
			if(data==null){
				return this._all(sql,fn);
			}
			var r=sqlstr(sql,data);
			return this._all(r.sql,r.data,fn);
		},
		_all:function(sql,data,fn){
			throw "由子类实现";
		},	
		each:function(sql,data,fn){
			if(typeof data == "function"){
				fn=data;	
				data=null;
			}
			if(data==null){
				return this._each(sql,fn);
			}
			var r=sqlstr(sql,data);
			return this._each(r.sql,r.data,fn);
		},
		_each:function(sql,data,fn){
			throw "由子类实现";
		}
	});

	return diqye;
}));